package com.haierp.service.logistics.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.haierp.util.yitao.YtDimensionCodeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.exception.ErpCommonException;
import com.haierp.model.ErpOrder;
import com.haierp.model.ShippingOrder;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IShippingOrderService;
import com.haierp.service.logistics.IYoukeService;
import com.haierp.service.xiaohongshu.IXiaohongshuService;
import com.haierp.service.youzan.IYzService;
import com.haierp.util.DimensionCodeUtil;
import com.haierp.util.HttpClientUtil;
import com.wangzhixuan.commons.base.BaseController;

import net.sf.json.JSONObject;

@Service("youkeService")
public class YoukeServiceImpl extends BaseController implements IYoukeService {
    @Autowired
    private IShippingOrderService shippingOrderService;

    @Autowired
    private IYzService yzService;

    @Autowired
    private IXiaohongshuService xiaohongshuService;

    @Autowired
    private IErpOrderService erpOrderService;

    private static Map<String, Object> baseParam = new HashMap<String, Object>();
    private static Map<String, Object> baseFoodParam = new HashMap<String, Object>();
    private static Map<String, Object> baseMilkParam = new HashMap<String, Object>();
    private static Map<String, Object> baseFinancialParam = new HashMap<String, Object>();
    private static Map<String, Object> ybBsParam = new HashMap<String, Object>();
    private static Map<String, Object> ybFoodParam = new HashMap<String, Object>();
    private static Map<String, Object> ybBagParam = new HashMap<String, Object>();

    static {
        baseParam.put("warehouse_id", "ORB");
        baseParam.put("ware_house_id", "ORB");
        //baseParam.put("warehouse_id", "JPT");
        //baseParam.put("ware_house_id", "JPT");
        baseParam.put("username", "winniegu@iruhua.com");
        baseParam.put("password", "2f900ceee5e75ee84c7cc96142619db405cb613729d8fa7f3dea68093321b7e7");

        baseFoodParam.put("warehouse_id", "ORB");
        baseFoodParam.put("ware_house_id", "ORB");
        baseFoodParam.put("client_identifier", "YXRHFDA");
        baseFoodParam.put("username", "YXRHFDA@yyox.com");
        baseFoodParam.put("password", "bd445c371eaec8570e1603862661fc75cb6d53774b04a0501c21efaaa5e471eb");

        baseMilkParam.put("warehouse_id", "AUX");
        baseMilkParam.put("ware_house_id", "AUX");
        baseMilkParam.put("client_identifier", "YXAUARH");
        baseMilkParam.put("username", "airuhua@qq.com");
        baseMilkParam.put("password", "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92");

        /*邮客经济线路*/
        baseFinancialParam.put("warehouse_id", "ORB");
        baseFinancialParam.put("ware_house_id", "ORB");
        baseFinancialParam.put("client_identifier", "YXRHECO");
        baseFinancialParam.put("username", "YXRHECO@yyox.com");
        baseFinancialParam.put("password", "18138372fad4b94533cd4881f03dc6c69296dd897234e0cee83f727e2e6b1f63");

        /*艺博包税线*/
        ybBsParam.put("warehouse_id", "ORB");
        ybBsParam.put("ware_house_id", "ORB");
        ybBsParam.put("username", "783167068@qq.com");
        ybBsParam.put("password", "7e01863550f52cd3aa9803da022d78161642f7c3ef90a697cfb8440623cecd2e");

        /*艺博食品线*/
        ybFoodParam.put("warehouse_id", "ORB");
        ybFoodParam.put("ware_house_id", "ORB");
        ybFoodParam.put("username", "YXYBFDA@yyox.com");
        ybFoodParam.put("password", "70d7c0f7abbec2dddc95436f010ebf3fee1e7beb88fca2413c87a1bd49ee3842");

        /*箱包线*/
        ybBagParam.put("warehouse_id", "ORB");
        ybBagParam.put("ware_house_id", "ORB");
        ybBagParam.put("username", "YXRHMXB@yyox.com");
        ybBagParam.put("password", "14c6b1bc5b0d59f060680a90a59b8aa2708a36c9701da6f87360eaf432533279");

    }

    private String priceUnit = "USD";
    //private String priceUnit = "JPY";

    @Override
    public void createOrder(Long id) {
        ShippingOrder shippingOrder = shippingOrderService.selectById(id);
        if (shippingOrder == null) {
            throw new ErpCommonException("发货单号异常");
        }

        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> paramDetail = new HashMap<String, Object>();
        if (shippingOrder.getCompanyId() == 1L) {
            if (shippingOrder.getType() == 6) {    //邮客食品线
                paramDetail.putAll(baseFoodParam);
            } else if (shippingOrder.getType() == 7) {//邮客奶粉线
                paramDetail.putAll(baseMilkParam);
            } else if (shippingOrder.getType() == 10) {//邮客经济线
                paramDetail.putAll(baseFinancialParam);
            } else {
                paramDetail.putAll(baseParam);
            }
        } else if (shippingOrder.getCompanyId() == 2L) {
            if (shippingOrder.getType() == 11) {
                paramDetail.putAll(ybFoodParam);
            } else if (shippingOrder.getType() == 12) {
                paramDetail.putAll(ybBsParam);
            }
        } else {
            if (shippingOrder.getType() == 17) {
                paramDetail.putAll(ybBagParam);
            }
        }

        paramDetail.put("buyer_name", shippingOrder.getReceiver());
        if (StringUtil.isNotBlank(shippingOrder.getIdCard())) {
            paramDetail.put("buyer_idcard", shippingOrder.getIdCard());
        } else {
            paramDetail.put("buyer_idcard", "111111111111111111");
        }

        paramDetail.put("buyer_mobile", shippingOrder.getTelephone());
        paramDetail.put("buyer_province", shippingOrder.getReceiverState());
        paramDetail.put("buyer_city", shippingOrder.getReceiverCity());
        paramDetail.put("buyer_district", shippingOrder.getReceiverDistrict());
        paramDetail.put("buyer_adress", shippingOrder.getAddressDetail());
        paramDetail.put("buyer_zipcode", "000000");
        paramDetail.put("customer_ref_no", shippingOrder.getShippingNo());
        if (shippingOrder.getType() == 7) {//邮客奶粉线  SKU模式
            paramDetail.put("api_order_type", "SKU");
        } else {
            paramDetail.put("api_order_type", "PKG");
        }

        List<Map<String, Object>> goodsList = new ArrayList<>();
        List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrder.getErpOrderId());
        ErpOrderList.forEach(erpOrder -> {
            Map<String, Object> goods = new HashMap<String, Object>();
            goods.put("sku_id", erpOrder.getSkuId());
            goods.put("upc", erpOrder.getUpc());
            String itemName = erpOrder.getItemName();
            itemName = itemName.replace("直邮", "");
            itemName = itemName.replace("拼邮", "");
            itemName = itemName.replace("包税", "");
            goods.put("name", itemName);
            goods.put("cny_name", erpOrder.getItemName());
            goods.put("category", erpOrder.getCategoryName());
            goods.put("brand", erpOrder.getBrand());
            StringBuffer spec = new StringBuffer();
            if (StringUtil.isNotBlank(erpOrder.getColor())) {
                spec.append(",Color:" + erpOrder.getColor());
            }
            if (StringUtil.isNotBlank(erpOrder.getScale())) {
                spec.append(",Size:" + erpOrder.getScale());
            }
            if (spec.length() > 0) {
                goods.put("spec", spec.toString().substring(1));
            }
            goods.put("price_unit", priceUnit);
            if (shippingOrder.getType() == 6) { // 邮客食品线 （更改价格方便核对）
                if (erpOrder.getPurchasePrice() > 1.00) {
                    if (erpOrder.getUnitItem() == 1) {
                        goods.put("declared_price", erpOrder.getPurchasePrice() * erpOrder.getUnitQuantity()); //组合商品推价格
                    } else {
                        goods.put("declared_price", erpOrder.getPurchasePrice());
                    }
                } else {
                    if (erpOrder.getSalePrice() * 0.7 > 100.00) {
                        goods.put("declared_price", getDeclaredPrice(99.00));
                    } else {
                        goods.put("declared_price", getDeclaredPrice(erpOrder.getSalePrice() * 0.7));
                    }
                }

            } else if (shippingOrder.getType() == 11 || shippingOrder.getType() == 12) { //一博推送价格逻辑
                if (erpOrder.getPurchasePrice() != null) {
                    goods.put("declared_price", erpOrder.getPurchasePrice());
                } else {
                    goods.put("declared_price", getDeclaredPrice(erpOrder.getSalePrice()));
                }
            } else {
                goods.put("declared_price", getDeclaredPrice(erpOrder.getSalePrice()));
            }
            goods.put("count", erpOrder.getQuantity());
            goods.put("oversea_express_no", shippingOrder.getShippingNo());
            if (shippingOrder.getType() == 7) {    //邮客奶粉线
                goods.put("sku_id", erpOrder.getThirdSkuCode());
                goods.put("upc", erpOrder.getUpc());
                goods.put("price_unit", "CNY");
                goods.put("declared_price", erpOrder.getSalePrice());
                goods.put("count", erpOrder.getQuantity());
                goods.put("oversea_express_no", "");
            }
            goodsList.add(goods);
        });
        paramDetail.put("goods_list", goodsList);
        param.put("param", paramDetail);
        JSONObject jsonObject = HttpClientUtil.post("https://api.yyox.com/createOrder", null, param, "1");
        JSONObject data = jsonObject.getJSONObject("data");
        shippingOrder.setLogisticNo((String) data.get("transfer_id"));
        shippingOrder.setTplPkgStatus("预报的未入库");
        shippingOrderService.updateSelectiveById(shippingOrder);
        if (!shippingOrder.getLogisticNo().equals("")) {
            if (ErpOrderList.size() == 1 && ErpOrderList.get(0).getSalesName().equals("有赞")) {
                Map<String, String> LogisticsCompanyKey = yzService.youzanGetLogisticsCompany();
                EntityWrapper<ErpOrder> erpList = new EntityWrapper<ErpOrder>();
                erpList.where("target_no={0}", ErpOrderList.get(0).getTargetNo());
                List<ErpOrder> list = erpOrderService.selectList(erpList);
                if (list.size() == 1 && list.get(0).getLogisticType() == 0) {//拼邮的强制不给有赞自动发货
                    yzService.youzanSendLogisticsOnline(ErpOrderList.get(0).getTargetNo(), shippingOrder.getLogisticNo(), LogisticsCompanyKey.get("e邮客"));
                }
            } else if (ErpOrderList.get(0).getSalesName().equals("coolforkids") || ErpOrderList.get(0).getSalesName().equals("superladies")) {
                Map<String, String> xhsGetLogisticsCompany = null;
                if ("superladies".equals(ErpOrderList.get(0).getSalesName())) {
                    xhsGetLogisticsCompany = xiaohongshuService.xhsGetLogisticsCompany("SL");
                } else {
                    xhsGetLogisticsCompany = xiaohongshuService.xhsGetLogisticsCompany("CFK");
                }
                EntityWrapper<ErpOrder> erpList = new EntityWrapper<ErpOrder>();
                erpList.where("target_no={0}", ErpOrderList.get(0).getTargetNo());
                List<ErpOrder> list = erpOrderService.selectList(erpList);
                this.logger.error("小红书后台回填物流单号: " + ErpOrderList.get(0).getTargetNo());
                String path = "/ark/open_api/v0/packages/" + list.get(0).getTargetNo();
                Map<String, String> params = new HashMap<>();
                params.put("status", "shipped");
                params.put("express_company_code", xhsGetLogisticsCompany.get("邮客全球速递"));
                params.put("express_no", shippingOrder.getLogisticNo());
                try {
                    if ("superladies".equals(ErpOrderList.get(0).getSalesName())) {
                        DimensionCodeUtil.redBookHttpRequest(path, params, "PUT", "SL");
                    } else {
                        DimensionCodeUtil.redBookHttpRequest(path, params, "PUT", "CFK");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (ErpOrderList.get(0).getSalesName().equals("一桃平台") || ErpOrderList.get(0).getSalesId().equals(46)) {
                Map<String, Object> params = new HashMap<>();
                String path = "/yitao/api/order/deliver";
                try {
                    EntityWrapper<ErpOrder> erpList = new EntityWrapper<ErpOrder>();
                    erpList.where("target_no={0}", ErpOrderList.get(0).getTargetNo());
                    List<ErpOrder> list = erpOrderService.selectList(erpList);
                    params.put("deliveryCompanyName", "邮客全球速递");//快递名称
                    params.put("orderCode", list.get(0).getTargetNo());//一桃订单ID
                    params.put("deliveryNo", shippingOrder.getLogisticNo());//快递编号
                    List<Long> itemIdList = Lists.newArrayList();
                    if (list != null && list.size() != 0) {
                        for (ErpOrder erpOrder : list) {
                            itemIdList.add(erpOrder.getItemId());
                        }
                        if (itemIdList != null && itemIdList.size() != 0) {
                            params.put("itemIdList", itemIdList);
                        }
                    }
                    YtDimensionCodeUtil.yitaoHttpPostRequest(path, params, "post");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void inboundStatus(String shippingNo) {
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> paramDetail = new HashMap<String, Object>();
        paramDetail.putAll(baseParam);
        paramDetail.put("oversea_express_no", shippingNo);

        param.put("param", paramDetail);
        //JSONObject ttt = post("https://api.yyox.com/inboundStatus", null, param, "1");
        String ttt = HttpClientUtil.post("https://api.yyox.com/inboundStatus", null, param, "1", "2");
        System.out.println(ttt);
    }

    @Override
    public void orderStatus(String transferId) {
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> paramDetail = new HashMap<String, Object>();
        paramDetail.put("transfer_id", transferId);
        param.put("param", paramDetail);
        //JSONObject ttt = post("https://api.yyox.com/orderStatus", null, param, "1");
        String ttt = HttpClientUtil.post("https://api.yyox.com/orderStatus", null, param, "1", "2");
        System.out.println(ttt);
    }

    private String getDeclaredPrice(Double salePrice) {
        salePrice = salePrice / 7;
        return String.format("%.2f", salePrice);
    }
}